<template>
  <div class="divBox relative">
    <el-card class="box-card">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="课程码" name="first">
          <div class="clearfix">
            <div class="container mt-1">
              <el-form inline size="small">
                <el-form-item label="类型：">
                  <el-select v-model="tableFrom.type" placeholder="请选择类型" @change="seachCodeList">
                    <el-option key="1" label="新品时刻" value="1"></el-option>
                    <el-option key="2" label="活动时刻" value="2"></el-option>
                  </el-select>
                </el-form-item>
              </el-form>
            </div>
            <el-button size="small" type="primary" @click="showAddPlsk" class="mr10" v-hasPermi="['admin:course:save']">新增
            </el-button>
          </div>
          <el-table
            v-loading="listLoading"
            :data="tableData.data"
            style="width: 100%"
            size="mini"
            :highlight-current-row="true"
            :header-cell-style=" {fontWeight:'bold'}"
          >
            <el-table-column
              prop="id"
              label="ID"
              min-width="50"
            />
            <el-table-column label="标题"
                             prop="name"
                             min-width="150"
                             :show-overflow-tooltip="true"
            >
            </el-table-column>
            <el-table-column label="活动图片" min-width="80">
              <template slot-scope="scope">
                <div class="demo-image__preview" v-if="scope.row.sliderImage">
                  <el-image
                    style="width: 36px; height: 36px"
                    :src="scope.row.sliderImage[0]"
                    :preview-src-list="scope.row.sliderImage"
                  />
                </div>
              </template>
            </el-table-column>
            <el-table-column label="副标题"
                             prop="subName"
                             :show-overflow-tooltip="true"
            >
            </el-table-column>
            <el-table-column
              prop="label"
              label="标签"
              min-width="70"
              align="center">
            </el-table-column>
            <el-table-column
              prop="sort"
              label="排序"
              min-width="70"
              align="center"
            />

            <el-table-column
              label="添加时间"
              min-width="120"
              align="center"
            >
              <template slot-scope="scope">
                <span>{{ scope.row.createTime | dataFormat }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="150" fixed="right" align="center">
              <template slot-scope="scope">
                <el-button type="text" size="small" class="mr10" v-hasPermi="['admin:product:info']" @click="showEdit(scope.row)">编辑</el-button>
                <el-button type="text" size="small" @click="handleDelete(scope.row)"
                           v-hasPermi="['admin:product:delete']"
                >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="block">
            <el-pagination
              :page-sizes="[20, 40, 60, 80]"
              :page-size="tableFrom.limit"
              :current-page="tableFrom.page"
              layout="total, sizes, prev, pager, next, jumper"
              :total="tableData.total"
              @size-change="handleSizeChange"
              @current-change="pageChange"
            />
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <el-dialog :visible.sync="plskAddDialog.visible" :title="plskAddDialog.form.id?'章节':'新增'" :before-close="clearPlskDialog" center width="60%" append-to-body>
      <el-form ref="courseFormValidate" v-loading="plskAddDialog.loading" class="formValidate mt20" :rules="plskAddDialog.rule"
               :model="plskAddDialog.form" label-width="120px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="标题：" prop="name">
              <el-input v-model="plskAddDialog.form.name" maxlength="249" placeholder="请输入标题"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="副标题：" prop="subName">
              <el-input v-model="plskAddDialog.form.subName" maxlength="249" placeholder="请输入副标题"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类型：">
              <el-select v-model="plskAddDialog.form.type" style="width: 100%" placeholder="请选择类型" @change="seachCodeList">
                <el-option key="1" label="新品时刻" value="1"></el-option>
                <el-option key="2" label="活动时刻" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序：" prop="sort">
              <el-input v-model="plskAddDialog.form.sort" type="number" placeholder="请输入排序"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="标签：" prop="name">
              <el-tag
                :key="item"
                style="margin-right: 5px"
                v-for="item in plskAddDialog.form.label"
                closable
                :disable-transitions="false"
                @close="removeLabel(item)">
                {{item}}
              </el-tag>
              <el-input
                class="input-new-tag"
                v-if="plskAddDialog.inputVisible"
                v-model="plskAddDialog.inputValue"
                style="width: 100px"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm"
                @blur="handleInputConfirm"
              >
              </el-input>
              <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>

              <!--                <el-input v-model="courseLabelList" maxlength="249" placeholder="请输入课程名称" :disabled="isDisabled"/>-->
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="商品轮播图：" prop="sliderImage">
              <div class="acea-row">
                <div
                  v-for="(item,index) in plskAddDialog.form.sliderImage"
                  :key="index"
                  class="pictrue"
                  draggable="true"
                  @dragstart="handleDragStart($event, item)"
                  @dragover.prevent="handleDragOver($event, item)"
                  @dragenter="handleDragEnter($event, item)"
                  @dragend="handleDragEnd($event, item)"
                >
                  <img :src="item">
                  <i v-if="!plskAddDialog.isDisabled" class="el-icon-error btndel" @click="handleRemove(index)"/>
                </div>
                <div v-if="plskAddDialog.form.sliderImage.length<10 && !plskAddDialog.isDisabled" class="upLoadPicBox" @click="modalPicTap('2')">
                  <div class="upLoad">
                    <i class="el-icon-camera cameraIconfont" />
                  </div>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="详情：" prop="description">
              <ueditor-from v-model="plskAddDialog.form.description" :content="plskAddDialog.form.description" />
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <span slot="footer" class="dialog-footer">
            <el-button @click="resetForm('courseFormValidate') ">取 消</el-button>
            <el-button type="primary" @click="addCourseList">确 定</el-button>
          </span>
    </el-dialog>

  </div>
</template>

<script>
import {
  addCourseListApi, deleteCourseListApi, updateCourseListApi
} from "@/api/course";
import {categoryApi} from "@/api/store";
import {addPlskApi, deletePlskApi, plskInfoApi, plskLstApi, updatePlskApi} from "@/api/plsk";

export default {
  name: 'ProductList',
  data() {
    return {
      activeName:'first',
      courseId:null,
      fullscreenLoading:false,

      merCateList:[],
      ruleValidate: {},
      tableFrom: {
        page: 1,
        limit: 20,
        type: '1'
      },
      courseListForm:{
        page:1,
        limit:20,
        total:0,
        courseId:null,
        list:[],
        label:[],
        loading:false
      },
      listLoading:false,
      tableData: {
        data: [],
        total: 0
      },
      plskAddDialog:{
        visible:false,
        loading:false,
        rules:{
          name: [
            { required: true, message: '请输入标题', trigger: 'blur' }
          ],
          subName: [
            { required: true, message: '请输入副标题', trigger: 'blur' }
          ],
          imageAttId: [
            { required: true, message: '请选择封面', trigger: 'change' }
          ],
          description: [
            { required: true, message: '请填写详情', trigger: 'blur' }
          ],
        },
        form:{
          id:null,
          name:'',
          subName:'',
          description:'',
          sort:1,
          label:[],
          type:'1',
          sliderImage:[]
        },
        inputVisible:false,
        inputValue:'',
        isDisabled:false
      }
    }
  },
  mounted() {
      this.getList()
  },
  methods:{
    handleClick(tab, event) {
      console.log(tab, event);
    },

    pageChange(page) {
      this.tableFrom.page = page
      this.getList()
    },
    handleSizeChange(val) {
      this.tableFrom.limit = val
      this.getList()
    },
    seachCodeList() {
      this.tableFrom.page = 1
      this.getList()
    },
    getList(){
      plskLstApi(this.tableFrom).then(res=>{
        let mdata = res.list
        for(let i in mdata){
          mdata[i].sliderImage = JSON.parse(mdata[i].sliderImage)
        }
        this.tableData.data=mdata
        this.tableData.total=res.total
      })
    },

    // 点击商品图
    modalPicTap (tit, num, i) {
      const _this = this
      if(_this.plskAddDialog.isDisabled) return;
      this.$modalUpload(function(img) {
        if(tit==='2'&& !num){
          if(img.length>10) return this.$message.warning("最多选择10张图片！");
          if(img.length + _this.plskAddDialog.form.sliderImage.length > 10) return this.$message.warning("最多选择10张图片！");
          img.map((item) => {
            _this.plskAddDialog.form.sliderImage.push(item.sattDir)
          });
        }
      },tit, 'content')
    },
    modalPicTap2 (tit, num, i) {
      const _this = this
      this.$modalUpload(function(img) {
        if(tit==='1'&& !num){
          console.log(img)
          _this.plskAddDialog.form.imageAttId = img[0].attId
          _this.plskAddDialog.form.image = img[0].sattDir
        }

      },tit, 'content')
    },
    showEdit(row){
      let obj = {
        id:row.id
      }
      plskInfoApi(obj).then(res=>{
        let mdata = res
        mdata.sliderImage = JSON.parse(mdata.sliderImage)
        mdata.label=mdata.label==''?[]:mdata.label.split(',')
        this.plskAddDialog.form=mdata
        this.showAddPlsk()
      })
    },
    showAddPlsk(){
      this.plskAddDialog.visible=true
    },
    resetForm(formName) {
      this.clearPlskDialog()
      this.$refs[formName].resetFields()
    },
    clearPlskDialog(){
      this.plskAddDialog.form={
        id:null,
        name:'',
        subName:'',
        description:'',
        sort:1,
        label: [],
        type:'1',
        sliderImage:[]
      }
      this.plskAddDialog.isDisabled=false
      this.plskAddDialog.inputVisible=false
      this.plskAddDialog.inputValue=''
      this.plskAddDialog.visible=false
    },
    addCourseList(){

      let obj = {
        name:this.plskAddDialog.form.name,
        subName:this.plskAddDialog.form.subName,
        description:this.plskAddDialog.form.description,
        sliderImage:JSON.stringify(this.plskAddDialog.form.sliderImage),
        sort:this.plskAddDialog.form.sort,
        type:this.plskAddDialog.form.type,
        label:this.plskAddDialog.form.label.join(',')
      }
      if(!this.plskAddDialog.form.id){
        addPlskApi(obj).then(res=>{
          this.getList()
          this.clearPlskDialog()
          this.$message.success('新增成功')
        }).catch(res=>{
          this.$message.error('新增失败')
        })
      }else{
        obj.id=this.plskAddDialog.form.id
        updatePlskApi(obj).then(res=>{
          this.getList()
          this.clearPlskDialog()
          this.$message.success('修改成功')
        }).catch(res=>{
          this.$message.error('修改失败')
        })
      }
    },
    handleDelete(row){
      deletePlskApi({id:row.id}).then(res=>{
        this.$message.success('删除成功')
        if(this.tableData.data.length==1&&this.tableFrom.page>1){
          this.tableFrom.page--
        }
        this.getList()
      })
    },

    // 移动
    handleDragStart (e, item) {
      if(!this.plskAddDialog.isDisabled) this.dragging = item;
    },
    handleDragEnd (e, item) {
      if(!this.plskAddDialog.isDisabled) this.dragging = null
    },
    handleDragOver (e) {
      if(!this.plskAddDialog.isDisabled) e.dataTransfer.dropEffect = 'move'
    },
    handleDragEnter (e, item) {
      if(!this.plskAddDialog.isDisabled){
        e.dataTransfer.effectAllowed = 'move'
        if (item === this.dragging) {
          return
        }
        const newItems = [...this.plskAddDialog.form.sliderImage]
        const src = newItems.indexOf(this.dragging)
        const dst = newItems.indexOf(item)
        newItems.splice(dst, 0, ...newItems.splice(src, 1))
        this.plskAddDialog.form.sliderImage = newItems;
      }
    },
    handleRemove (i) {
      this.plskAddDialog.form.sliderImage.splice(i, 1)
    },

    showInput() {
      this.plskAddDialog.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      let inputValue = this.plskAddDialog.inputValue;
      if (inputValue) {
        this.plskAddDialog.form.label.push(inputValue);
      }
      this.plskAddDialog.inputVisible = false;
      this.plskAddDialog.inputValue = '';
    },
    removeLabel(tag){
      this.plskAddDialog.form.label.splice(this.plskAddDialog.form.label.indexOf(tag), 1);
    }

  }
}
</script>

<style scoped lang="scss">
.pictrue{
  width: 60px;
  height: 60px;
  border: 1px dotted rgba(0,0,0,0.1);
  margin-right: 10px;
  position: relative;
  cursor: pointer;
  img{
    width: 100%;
    height: 100%;
  }
  video{
    width: 100%;
    height: 100%;
  }
}
</style>
